/**
 * 实现多个useState 同时调用的情况下，state无法代表多个数据的情况
 *      这里使用 hook 对象，存储所定义的数据
 *
 * */


let hook = {
    state: null, // 当前useState 中的state
    dispatch: null, // 当前useState 中的setState
    next: null // 下一个useState 中存储的hook 对象
}

const Dispatcher = (function () {
    let isMount = true,
        firstWorkInProgressHook = null,
        workInProgressHook = null

    function mountWorkInProgressHook() {
        let hook = {
            state: null, // 当前useState 中的state
            dispatch: null, // 当前useState 中的setState
            next: null // 下一个useState 中存储的hook 对象
        }
        //当前是没有存在的hook
        if (workInProgressHook === null) {
            firstWorkInProgressHook = workInProgressHook = hook
        } else {
            workInProgressHook = workInProgressHook.next = hook
        }
        return workInProgressHook
    }


    function updateInProgressHook() {
        let curHook = workInProgressHook;
        workInProgressHook = workInProgressHook.next;
        return curHook
    }


    function useState(initialValue) {
        let hook
        if (isMount) {
            hook = mountWorkInProgressHook()
            hook.state = initialValue
        } else {
            hook = updateInProgressHook()
        }

        hook.dispatch = function (newState) {
            // 避免重复渲染
            if (hook.state === newState) return
            hook.state = newState
            workInProgressHook = firstWorkInProgressHook;
            isMount = false
            scheduleWork(hook, newState);
        }
        return [hook.state, hook.dispatch]
    }

    //导出，供使用
    return {
        useState
    }
})()


/**
 * 调度，进行ui视图更新
 */
function scheduleWork(hook, newVal) {
    console.log(`ui 视图需要更新了！hook:${hook.state},newValue:${newVal}`)
}


function Counter() {
    let [count, setCount] = Dispatcher.useState(1);
    let [age, setAge] = Dispatcher.useState(10);


    setCount(count + 1)
    setAge(age + 1)
    // return (
    //     <>
    //         <p>Clicked {count} times</p>
    //         <button onClick={() => setCount(count + 1)}> Add count</button>
    //         <p>Age is {age}</p>
    //         <button onClick={() => setAge(age + 1)}> Add age</button>
    //     </>
    // );
}


Counter()





